package com.ctsi.security.app.controller;

import com.ctsi.commons.util.UtilValidate;
import com.ctsi.commons.util.response.Page;
import com.ctsi.framework.common.response.UnifiedResponse;
import com.ctsi.framework.security.util.SecurityUtil;
import com.ctsi.organise.common.api.OrganiseFactoryBean;
import com.ctsi.organise.common.api.PersonServiceProxy;
import com.ctsi.organise.common.api.UserLoginServiceProxy;
import com.ctsi.organise.common.model.Organise;
import com.ctsi.organise.common.model.Person;
import com.ctsi.organise.common.model.UserLogin;
import com.ctsi.security.PartySrole;
import com.ctsi.security.PermissionRole;
import com.ctsi.security.domain.RolePermission;
import com.ctsi.security.domain.SRole;
import com.ctsi.security.service.RoleSecurityService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

 

@Controller
public class UserRoleController {
	private static final Logger logger = LoggerFactory.getLogger(UserRoleController.class);
	private PermissionRole sroleService;
	private PartySrole secSRoleService;
	private RoleSecurityService roleSecurityService;
	private PersonServiceProxy personServiceProxy = OrganiseFactoryBean.getInstance().getPersonServiceProxy();
	private UserLoginServiceProxy userLoginServiceProxy;


	/**
	 * 登陆用户
	 * @param request
	 * @param response
	 * @return
	 */
	public ModelAndView userLoginIndex(HttpServletRequest request, HttpServletResponse response){
		return new ModelAndView("person/userLoginIndex");
	}
	
	public ModelAndView queryRoleIndex(HttpServletRequest request, HttpServletResponse response) {
		String loginName = request.getParameter("loginName");
		String partyId = request.getParameter("partyId");
		if(UtilValidate.isEmpty(loginName)){
			loginName = (String) request.getAttribute("loginName");
		}
		if(UtilValidate.isEmpty(partyId)){
			partyId = (String) request.getAttribute("partyId");
		}
		Organise organise =  personServiceProxy.getDefaultOrgan(partyId);
		String orgName = UtilValidate.isNotEmpty(organise.getShortName()) ? organise.getShortName(): organise.getOrganiseName();
		request.setAttribute("loginName", loginName);
		request.setAttribute("orgName", orgName);
		return new ModelAndView("organise/userLogin/userRole");
	}

	public UnifiedResponse<Page<SRole>> queryRole(HttpServletRequest request, HttpServletResponse response) {
		String loginId = request.getParameter("loginId");
		String start = request.getParameter("start");
		String roleName = request.getParameter("roleName");
		if (UtilValidate.isEmpty(start)) {
			start = "0";
		}
		if (UtilValidate.isEmpty(loginId)) {
			logger.warn("登录用户Id没有传进来！");
			return UnifiedResponse.ok(new Page<SRole>());
		}
		Map<String, Object> args = new HashMap<String, Object>();
		if (UtilValidate.isNotEmpty(roleName)) {
			args.put("roleName", roleName);
		}
		Page<SRole> page = secSRoleService.getSRolesByLoginId(loginId, args, Integer.parseInt(start));
		return UnifiedResponse.ok(page);
	}
	public UnifiedResponse<String> addPermissionsWithType(HttpServletRequest request, HttpServletResponse response) {
		String types = request.getParameter("types");
		String typenames = request.getParameter("typenames");
		String permisionIds = request.getParameter("permisionIds");
		String roleId = request.getParameter("loginId");
		String hasLowers = request.getParameter("hasLowers");
		String leafTypes = request.getParameter("leafTypes");
		String[] typesArray = types.split(",");
		String[] typenamesArray = typenames.split(",");
		String[] permisionIdsArray = permisionIds.split(",");
		String[] hasLowersArray = hasLowers.split(",");
		String[] leafTypesArray = leafTypes.split(",");
		StringBuilder sb = new StringBuilder();
		UserLogin userLogin=userLoginServiceProxy.findById(roleId);
		Person person = null;
		String name = "";
		if(userLogin != null){
			person = personServiceProxy.findPersonById(userLogin.getPartyId());
		}
		if(person!=null){
			name = person.getFullName();
		}
		for(int i=0;i<typesArray.length;i++){
			RolePermission rolePermission = new RolePermission();
			rolePermission.setPermissionId(permisionIdsArray[i]);
			rolePermission.setRoleId(roleId);
			rolePermission.setPermisionType(typesArray[i]);
			rolePermission.setPermisionTypeName(typenamesArray[i]);
			rolePermission.setHasLower(hasLowersArray[i]);
			rolePermission.setPermisionLeafType(leafTypesArray[i]);
			rolePermission.setType(RolePermission.TYPE_LOGINID);
			try{
				roleSecurityService.saveRolePermission(rolePermission);
			}catch(Exception e){
				logger.info("{}",e.getMessage());
				logger.debug("",e);
				if(sb.length()==0){
					sb.append(',');
				}
				sb.append(rolePermission.getPermisionTypeName());
			}
		}
		if(sb.length()==0){
		    return UnifiedResponse.ok("保存成功");
		}else{
		    return UnifiedResponse.ok("保存【"+sb.toString()+"】失败，其他成功");
		}
	}
	public UnifiedResponse<Void> removesPrem(HttpServletRequest request, HttpServletResponse response) {
		String types = request.getParameter("types");
		String ids = request.getParameter("ids");
		String loginId = request.getParameter("loginId");
		String permissionIds = request.getParameter("permissionIds");
		
		String[] typesArray = types.split(",");
		String[] idsArray = ids.split(",");
		String[] permissionIdsArray = permissionIds.split(",");
		
		int i=0;
		UserLogin userLogin=userLoginServiceProxy.findById(loginId);
		Person person = null;
		String name = "";
		if(userLogin != null){
			person = personServiceProxy.findPersonById(userLogin.getPartyId());
		}
		if(person!=null){
			name = person.getFullName();
		}
		for(String id:idsArray){
			String permissionId = permissionIdsArray[i];
			String type = typesArray[i++];
			if("1".equals(type)){
				sroleService.delUserRole(loginId, id);
			}
			if("2".equals(type)){
				roleSecurityService.removeRolePermission(id, permissionId);
			}
		}
		return UnifiedResponse.ok();
	}
	
	public UnifiedResponse<Page> queryRoleWithDataObject(HttpServletRequest request, HttpServletResponse response) {
		String loginId = request.getParameter("loginId");
		String start = request.getParameter("start");
		String roleName = request.getParameter("roleName");
		if (UtilValidate.isEmpty(start)) {
			start = "0";
		}

		if (UtilValidate.isEmpty(loginId)) {
			logger.warn("登录用户Id没有传进来！");
			return UnifiedResponse.ok(new Page<SRole>());
		}
//		Map<String, Object> args = new HashMap<String, Object>();
//		if (UtilValidate.isNotEmpty(roleName)) {
//			args.put("roleName", roleName);
//		}
		//Page<SRole> page = secSRoleService.getSRolesByLoginId(loginId, args, Integer.parseInt(start));
		Page<Map<String,Object>> page = secSRoleService.queryPersonSec(SecurityUtil.getUser().getLoginId(),
                loginId, roleName, Integer.parseInt(start), Page.DEFAULT_PAGE_SIZE);
	//	Page<SRole> page = secSRoleService.getSRolesByLoginId(super.getCuruserLoginId(request),"sysModule","SELECT",loginId,args,Integer.parseInt(start));
		return UnifiedResponse.ok(page);
	}

    /**
     * 弹出窗口数据
     * @param request
     * @param response
     * @return
     */
	@SuppressWarnings("unchecked")
	public UnifiedResponse<Page<SRole>> queryRoleWin(HttpServletRequest request, HttpServletResponse response) {
		String start = request.getParameter("start");
		String roleName = request.getParameter("roleName");
		if (UtilValidate.isEmpty(start)) {
			start = "0";
		}
	
//		当前登录用户
		String userLogin= SecurityUtil.getUser().getLoginId();
		String dataObjectType="sysModule";
		String action="SELECT";
		Page<SRole> page = secSRoleService.queryRoleByName(userLogin, dataObjectType, action, Page.DEFAULT_PAGE_SIZE, Integer.parseInt(start),roleName);
		return UnifiedResponse.ok(page);
	}

    /**
     * 删除用户角色
     * @param request
     * @param response
     * @return
     */
	public ModelAndView delUserRole(HttpServletRequest request, HttpServletResponse response) {
		String loginId = request.getParameter("loginId");
		String roleIds = request.getParameter("roleIds");
		if (UtilValidate.isEmpty(loginId) || UtilValidate.isEmpty(roleIds)) {
			logger.warn("登录用户Id或角色Ids没有传递过来！");
			return queryRoleIndex(request, response);
		}
		sroleService.delUserRoles(loginId, roleIds);
		return queryRoleIndex(request, response);
	}

    /**
     * 增加用户角色
     * @param request
     * @param response
     * @return
     */
	public ModelAndView addUserRole(HttpServletRequest request, HttpServletResponse response){
		String loginId = request.getParameter("loginId");
		String roleIds = request.getParameter("roleIds");
		String loginName=request.getParameter("loginName");
		String partyId=request.getParameter("partyId");
		if (UtilValidate.isEmpty(loginId) || UtilValidate.isEmpty(roleIds)) {
			logger.warn("登录用户Id或角色Ids没有传递过来！");
			return queryRoleIndex(request, response);
		}
		for(String roleId : roleIds.split(",")){
		    sroleService.addUserRoles(loginId,loginName,partyId,roleId);
		}
		return queryRoleIndex(request, response);
	}

}
